<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use sms\SendCode;
use think\facade\Session;
class Login extends Controller
{
    //登陆
    public function index()
    {
        $data=Session::get('user');
        if($data){
            return $this->fetch('user/user',['data'=>$data]);
        }else{
            return $this->fetch('index');
        }
        
    }
    //注册
    public function zhuce(){
        return $this->fetch('zhuce');
    }
    //登陆查询
    public function login(){
        $data=input('post.');
        Session::set('user',$data['user']);
        $date=Db::table('user')->where('user','=',$data['user'])->find();

        if ($date){
            if($date['pwd']==md5($data['pwd'])){
                echo json_encode(['code'=>200,'msg'=>'成功']);die;
            }else{
                echo json_encode(['code'=>4003,'msg'=>'密码错误']);die;
            }
        }else{
            echo json_encode(['code'=>4003,'msg'=>'用户名错误或不存在']);die;
        }
    }
    //忘记密码
    public function pass(){
        return $this->fetch('pass');
    }
    //发送短信
    public function note(){
        $data=input('post.');
        $code=rand(1000,9999);
        $Rest = new SendCode();
        $Rest->sendTemplateSMS($data['tel'],array($code,'3'),"1");
        \think\facade\Session::set('c_code',$c_code);
    }
    public function zhuce_do(){
        $data=input('post.');
        if(empty(\think\facade\Session::has('c_code'))){
             echo json_encode(['code'=>4003,'msg'=>'验证码不存在']);die;
        }

        $c_code=\think\facade\Session::get('c_code');
        if($data['code']!=$c_code){
            echo json_encode(['code'=>4003,'msg'=>'短信验证码不正确，请重新获取']);die;
        }
        $res=Db::table('user')->insert(['user'=>$data['user'],'pwd'=>md5($data['password'])]);
        if($res){
            echo json_encode(['code'=>200,'msg'=>'添加成功']);die;
        }else{
            echo json_encode(['code'=>4003,'msg'=>'添加失败']);die;
        }
    }

    public function pass_do(){
        $data=input('post.');
        // $c_code=dump(cookie('c_code'));
        // if($data['code']!=$c_code){
        //     echo json_encode(['code'=>4003,'msg'=>'短信验证码不正确，请重新获取']);die;
        // }
        $res=Db::table('user')->where('user',$data['tel'])->update(['pwd'=>md5($data['password'])]);
        if($res){
            echo json_encode(['code'=>200,'msg'=>'修改成功']);die;
        }else{
            echo json_encode(['code'=>4003,'msg'=>'修改失败']);die;
        }
    }
}
